package stack;

import org.junit.Test;

import java.util.Stack;

/*
 *@description 基本计算器
 *@author hkfan
 *@version 1.0
 *@create 2025/6/6 16:00
 */
public class LeetCode_224 {
    @Test
    public void test(){
        System.out.println(calculate("1-(-2)"));
    }
    public int calculate(String s) {
        //1. 定义
        int sign = 1,num=0,res=0;
        Stack<Integer> stack = new Stack<>();

        //2. 循环遍历
        for (int i = 0; i < s.length(); i++) {
            char c = s.charAt(i);
            if (Character.isDigit(c)){
                num=num*10+(c-'0');
            } else if (c=='(') {
                stack.add(res);
                stack.add(sign);
                res=0;sign=1;
            } else if (c=='+' || c=='-') {
                res = (sign==1)?res+num:res-num;
                num=0;
                sign=(c=='+')?1:0;
            } else if (c==')') {
                res = (sign==1)?res+num:res-num;
                sign=1;
                num=0;
                Integer pop1 = stack.pop();
                Integer pop2 = stack.pop();
                res = (pop1==1)?pop2+res:pop2-res;
            }
        }
        //3. 返回
        return (sign==1)?res+num:res-num;


    }

}
